const connection = require('../app/database')

class FriendService{
  // 发送好友申请
  async applyAdd(u_id, f_id, f_name, state) {
    const statement = `insert into friend (user_id, friend_id, markname, state) values (?, ?, ?, ?);`
    const [result] = await connection.execute(statement, [u_id, f_id, f_name, state])
    return result
  }
  // 查看是否发送了好友申请 
  async getApplyById(u_id, f_id) {
    const statement = `select * from friend where user_id = ? and friend_id = ?;`
    const [result] = await connection.execute(statement, [u_id, f_id])
    return result.length === 0 ? false : true
  }
  // 获取好友申请列表
  async getApplyListById(userId) {
    const statement = `select * from friend where user_id = ? and state = 1`
    const [result] = await connection.execute(statement, [userId])
    return result
  }
  // 同意好友申请
  async agreeApply(userId, f_id) {
    const statement = `update friend set state = 0 where user_id = ? and friend_id = ?;`
    const [result] = await connection.execute(statement, [userId, f_id])
    return result
  }
  // 获取好友列表
  async getFriendListById(userId) {
    const statement = `select * from friend where user_id = ? and state = 0`
    const [result] = await connection.execute(statement, [userId])
    return result
  }
  // 删除好友或拒绝申请
  async removeFriend(userId, f_id) {
    const statement =  `delete from friend where user_id = ? and friend_id = ?;`
    const [result] = await connection.execute(statement, [userId, f_id])
    return result
  }
  // 修改好友备注
  async rename(userId, f_id, newName) {
    const statement = `update friend set markname = ? where user_id = ? and friend_id = ?;`
    const [result] = await connection.execute(statement, [newName, userId, f_id])
    return result
  }
}

module.exports = new FriendService()